import os
from pathlib import Path

# 定义合并Markdown文件的函数
def merge_md_files(directory, output_file):
    # 确保输出文件不在合并列表中
    output_path = Path(directory) / output_file
    if output_path.exists():
        output_path.unlink()

    # 使用Path打开输出文件准备写入，指定UTF-8编码
    with output_path.open('w', encoding='utf-8') as outfile:
        
        # 遍历目录
        for file_path in Path(directory).rglob('*.md'):
            # 检查文件是否是目标输出文件
            if file_path != output_path:
                try:
                    # 使用Path打开并读取.md文件内容，指定UTF-8编码
                    with file_path.open('r', encoding='utf-8') as infile:
                        # 将内容写入输出文件
                        outfile.write(infile.read() + '\n\n\n')
                except UnicodeDecodeError:
                    print(f"Skipping file {file_path} due to encoding error.")
    print(output_path, "已经输出.")


current_dir = os.getcwd()
for dir_name in os.listdir(current_dir):
    if dir_name.startswith('.'):  # 跳过以“.”开头的目录
        continue
    dir_path = os.path.join(current_dir, dir_name)
    if os.path.isdir(dir_path):
        # 以目录为项目，执行merge_md_files函数
        merge_md_files(dir_name, 'Readme.md')

print("合并完成!")